<template>
  <div class="classroom-selector">
    <h1>教室查询系统</h1>
    <!--  添加一个提示：注意：本页查询的教室基于过期课表故仅供参考，请以教务系统查询为准。-->
    <div class="tip">
      <p>注意：本页查询的教室基于过期课表故仅供参考，请以教务系统查询为准。</p>
    </div>
    <el-form :model="form" label-width="120px" ref="formRef">
      <el-form-item label="学年学期:" prop="schoolTerm">
        <el-input v-model="form.schoolTerm" placeholder="自动检测或手动输入"></el-input>
      </el-form-item>
      <el-form-item label="第几周:" prop="week">
        <el-input-number v-model="form.week" :min="1" :max="20" placeholder="第几周"></el-input-number>
      </el-form-item>
      <el-form-item label="星期/节次:" prop="dayPeriod" :rules="new_class_time">
        <el-input v-model="form.dayPeriod" placeholder="星期/节次" ></el-input>
      </el-form-item>
<!--      空两行-->
      <br>

      </br>
      <el-form-item>
        <el-button type="primary" @click="getAvailableRooms" :loading="check_loading">查询可用教室</el-button>
      </el-form-item>
    </el-form>
    <ul v-if="availableRooms.length > 0">
      <li v-for="room in availableRooms" :key="room">{{ room }}</li>
    </ul>
    <p v-else>没有可用教室。</p>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElInputNumber, ElMessage } from 'element-plus';
import { jsonApi } from '@/global.js';

const formRef = ref(null);
const check_loading = ref(false);
const form = reactive({
  schoolTerm: '',
  week: null,
  dayPeriod: ''
});
const availableRooms = ref([]);

const new_class_time = ref([
  { required: true, message: '字段不能为空', trigger: 'blur' },
  {
    validator: (rule, value, callback) => {
      const regex = /^(一|二|三|四|五|六|日)\/(\d{1,2}(-\d{1,2})?)$/;
      const match = value.match(regex);

      if (match) {
        const sessionPart = match[2];
        const sessions = sessionPart.split('-');

        if (sessions.length === 1) {
          const session = parseInt(sessions[0], 10);
          if (session >= 1 && session <= 13) {
            return callback();
          }
        } else if (sessions.length === 2) {
          const startSession = parseInt(sessions[0], 10);
          const endSession = parseInt(sessions[1], 10);
          if (startSession >= 1 && endSession <= 13 && startSession < endSession) {
            return callback();
          }
        }
      }

      return callback(new Error('格式错误，请按照 星期/节次 格式，例： 二/1-3 '));
    },
    trigger: 'blur'
  }
]);

function getSchoolTerm(date) {
  const currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1;

  let startYear, endYear;
  if (currentMonth >= 8 || currentMonth <= 1) {
    startYear = currentYear;
    endYear = currentYear + 1;
  } else {
    startYear = currentYear - 1;
    endYear = currentYear;
  }

  let term = currentMonth >= 2 && currentMonth <= 7 ? '春季学期' : '秋季学期';

  return `${startYear}-${endYear}学年${term}`;
}

async function getAvailableRooms() {
  try {
    check_loading.value = true;
    const body = {
      "term": form.schoolTerm,
      "week": form.week,
      "new_class_time": form.dayPeriod
    };
    const respond = await jsonApi('/courseadjustmentmanagement/getcaninputroom/', JSON.stringify(body));
    const roomsData = await respond.json();
    availableRooms.value = roomsData['can_use_room'];
    check_loading.value = false;
  } catch (e) {
    ElMessage.error('获取教室列表失败: ' + e);
    check_loading.value = false;
  }
}

onMounted(() => {
  form.schoolTerm = getSchoolTerm(new Date());
});
</script>

<style scoped>
.classroom-selector {
  width: 300px;
  margin: auto;
}
.el-input, .el-input-number {
  display: block;
  margin-bottom: 10px;
}
.el-button {
  display: block;
  margin-bottom: 10px;
}
</style>